import config from "../config";
const { baseUrl } = config;
const delay = config.isMock ? 500 : 0;
function request(url, method = "GET", data = {}, headerOpt = {}) {
  const header = {
    "content-type": "application/json",
    // 有其他content-type需求加点逻辑判断处理即可
    ...headerOpt,
  };
  // 获取token，有就丢进请求头
  const tokenString = uni.getStorageSync("access_token");
  
  if (!tokenString && (!url.includes("login") && !url.includes("token"))) {
    uni.navigateTo({
      url: `/pages/login/login`,
      // url: `/pages/home/index`
    });
    uni.showToast({
      title: "请先登录",
      icon: "none",
    });
    return Promise.reject("请先登录");
  }
  if (tokenString) {
    header.Authorization = `Bearer ${tokenString}`;
  }
  return new Promise((resolve, reject) => {
    try {
      uni.request({
        url: baseUrl + url,
        method,
        data,
        dataType: "json",
        // 微信官方文档中介绍会对数据进行一次JSON.parse
        header,
        success(resData) {
          const res = resData?.data;
          setTimeout(() => {
            // HTTP状态码为0才视为成功
            if (res.code === 0) {
              resolve(res);
            } else if (res.code === 401) {
              uni.clearStorageSync();
              uni.navigateTo({
                url: `/pages/login/login`,
              });
              uni.showToast({
                title: "请先登录",
                icon: "none",
              });
              reject(res);
            } else {
              // console.log('请求失败', res);
              // wx.request的特性，只要有响应就会走success回调，所以在这里判断状态，非0的均视为请求失败
              reject(res);
            }
          }, delay);
        },
        fail: (err) => {
          uni.showModal({
            content: "网络异常，请检查",
            showCancel: false,
            success: (_) => {},
          });
          // 断网、服务器挂了都会fail回调，直接reject即可
          reject(err);
        },
      });
    } catch (error) {
      console.log("CatchClause", error);
      console.log("CatchClause", error);
      console.log("错误信息", error);
      reject(error);
    }
  });
}

// 导出请求和服务地址
export default request;
